<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item :label="$t('role_name')" prop="roleName">
        <el-input
          v-model="queryParams.roleName"
          :placeholder="$t('please_enter', { name: $t('role_name') })"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('role_description')" prop="remark">
        <el-input
          v-model="queryParams.remark"
          :placeholder="$t('please_enter', { name: $t('role_description') })"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >{{ $t("search") }}</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
          $t("reset")
        }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['employee:employeeHead:employeeHeadRole:add']"
          >{{ $t("add") }}</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="roleList"
      @selection-change="handleSelectionChange"
      border
      :max-height="tableHeight"
    >
      <el-table-column :label="$t('id_number')" align="center" prop="id" />
      <el-table-column
        :label="$t('role_name')"
        align="center"
        prop="roleName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="$t('role_description')"
        align="center"
        prop="remark"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="$t('creation_time')"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('action')"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['employee:employeeHead:employeeHeadRole:view']"
            >{{ $t("view") }}</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['employee:employeeHead:employeeHeadRole:edit']"
            >{{ $t("modify") }}</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['employee:employeeHead:employeeHeadRole:delete']"
            >{{ $t("delete") }}</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDataScope(scope.row)"
            v-hasPermi="['employee:employeeHead:employeeHeadRole:edit']"
            >{{ $t("permissions") }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      :page-sizes="[10,20,30,50,100, 200]"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        :disabled="lookView"
      >
        <el-form-item :label="$t('role_name')" prop="roleName">
          <el-input
            v-model="form.roleName"
            :placeholder="$t('please_enter', { name: $t('role_name') })"
          />
        </el-form-item>
        <el-form-item :label="$t('role_description')" prop="remark">
          <el-input
            v-model="form.remark"
            :placeholder="$t('please_enter', { name: $t('role_description') })"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!lookView">
        <el-button type="primary" @click="submitForm">{{
          $t("confirm")
        }}</el-button>
        <el-button @click="cancel">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>

    <!-- 配置权限对话框 -->
    <el-dialog
      title="设置权限"
      :visible.sync="authOpen"
      width="500px"
      append-to-body
    >
    <p style="padding-left: 30px;">{{ $t('role_name') }}:{{ authForm.roleName }}</p>
      <el-form ref="authForm" :model="authForm" label-width="100px">
        <el-form-item :label="$t('menu_permissions')">
          <el-checkbox
            v-model="menuExpand"
            @change="handleCheckedTreeExpand($event, 'menu')"
            >{{ $t("expand_collapse") }}</el-checkbox
          >
          <el-checkbox
            v-model="menuNodeAll"
            @change="handleCheckedTreeNodeAll($event, 'menu')"
            >{{ $t("elect_all_don_select_all") }}</el-checkbox
          >
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            empty-text="loading.."
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="authSubmitForm">{{
          $t("confirm")
        }}</el-button>
        <el-button @click="authCancel">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRole,
  getRole,
  delRole,
  addRole,
  updateRole,
  getMenuTree,
  permissionSettings,
} from "@/api/custom/employeeHeadRole";
export default {
  name: "Role",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: undefined,
        remark: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        roleName: [
          {
            required: true,
            message: this.$t("cannot_empty", { name: this.$t("role_name") }),
            trigger: "blur",
          },
        ],
      },
      lookView: false,

      //权限弹窗
      authOpen: false,
      //权限表单
      authForm: {
        menuIdList: [],
      },
      // 是否显示弹出层（数据权限）
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      defaultProps: {
        children: "children",
        label: (data) => this.$t(data.label),
      },
      // 菜单列表
      menuOptions: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      listRole(this.queryParams).then((response) => {
        this.roleList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        roleName: undefined,
        remark: undefined,
      };
      this.lookView = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == "menu") {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == "dept") {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == "menu") {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
      } else if (type == "dept") {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
      }
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      console.log("🐛 ~ getMenuAllCheckedKeys ~ checkedKeys:", checkedKeys)
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();

      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = this.$t("add");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getRole(row.id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = this.$t("modify");
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      getRole(row.id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.lookView = true;
        this.title = this.$t("view");
      });
    },
    /** 分配数据权限操作 */
    handleDataScope(row) {
      this.reset();
      this.getMenuTree(row.id);
      this.authForm = row;
      this.authOpen = true;
    },
    getMenuTree(id) {
      getMenuTree(id).then((response) => {
        this.menuOptions = response.menus;
        let checkedKeys = response.checkedKeys;
        checkedKeys.forEach((v) => {
          this.$nextTick(() => {
            this.$refs.menu.setChecked(v, true, false);
          });
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id) {
            updateRole(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t("operation_successful"));
              this.open = false;
              this.getList();
            });
          } else {
            addRole(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t("operation_successful"));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.id || this.ids;
      this.$modal
        .confirm(this.$t("delete_data"))
        .then(function () {
          return delRole(roleIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t("operation_successful"));
        })
        .catch(() => {});
    },

    /** 设置权限提交 */
    authSubmitForm() {
      this.authForm.menuIdList = this.getMenuAllCheckedKeys();
      let data = {
        businessId: this.authForm.id,
        menuIds: this.authForm.menuIdList,
      };
      permissionSettings(data).then((response) => {
        this.$modal.msgSuccess(this.$t("operation_successful"));
        this.authOpen = false;
        this.getList();
      });
    },

    // 取消按钮
    authCancel() {
      this.authOpen = false;
      this.reset();
    },
  },
};
</script>
